# 题目: 430. 扁平化多级双向链表
多级双向链表中,除了指向下一个节点和前一个节点指针之外,它还有一个子链表指针,可能指向单独的双向链表。这些子列表也可能会有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
给你位于列表第一级的头节点,请你扁平化列表,使所有结点出现在单级双链表中。
# 示例1:
输入:head = [1,2,null,3]
输出:[1,3,2]
解释:
输入的多级列表如下图所示:
1---2---NULL
|
3---NULL
# 示例2:
输入:head = []
输出:[]
# 题解: 深度优先遍历
从头节点开始遍历,当此时遍历的node节点具备子链表指针时,进行递归处理,并保存此时node节点的下一跳,以便于子链表的连接。
# 代码
/**
* // Definition for a Node.
* function Node(val,prev,next,child) {
* this.val = val;
* this.prev = prev;
* this.next = next;
* this.child = child;
* };
*/
/**
* @param {Node} head
* @return {Node}
*/
var flatten = function(head) {
const dfs = (node)=>{
let cur = node
// 链表的最后一个节点
let last = null
while(cur){
let next = cur.next
if(cur.child){
const childList = dfs(cur.child)
// 绑定 child 节点
cur.next = cur.child
cur.child.prev = cur
if(next!=null){
childList.next = next
next.prev = childList
}
cur.child = null
last = childList
}else{
last = cur
}
cur = next
}
// 返回最后一个链表结点便于连接
return last
}
dfs(head)
return head
};